package core;

public class AddItemCommand extends Command
{
	private StorageUnit unit;
	private ProductManager pm;
	private ItemManager im;
	private CoreFacade core;
	private boolean productAdded;
	
	 /**
     * Adds the specified item to the storage unit. If item's product is already somewhere
     * in the storage unit tree, it must be added to the same group in the tree.
     * @param i item to be added
     * @param su storage unit to add the item to
     */
	public AddItemCommand(Item i, StorageUnit su)
	{
		super();
		initializeCommand(i,su,0,false);		
	}
	
	public AddItemCommand(Item i, StorageUnit su, int number, boolean pAdd)
	{
		super();
		initializeCommand(i,su,number, pAdd);
	}
	
	private void initializeCommand(Item i, StorageUnit su, int num, boolean pAdd)
	{
		item = i;
		unit = su;
		core = CoreFacade.getInstance();
		pm = core.getPM();
		im = core.getIM();
		addGroupMemberNumber = num;
		productAdded = pAdd;
	}
	
	@Override
	/**
	 * This method will perform the action for the first time
	 */
	public Item execute()
	{
		if(productAdded)
		{
			//System.out.println("Product Was Added most recently");
			// add the product to the system 
			try {
				core.addProduct(item.getProduct(), unit);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else
			;//System.out.println("Product Already Existed");
		try{
		if(!core.canAddItem(item.getBarcodeString()))
        	throw new Exception("Item cannot be added.");
		}
		catch(Exception e){return null;}
        //check if product is in storage unit
        ProductContainer pc = pm.getContainer(unit, item.getProduct());
        core.addItemPersistence(item);
        if(pc == null)
        {
        	//add product/item at su root level
        	pm.addProductToContainer(item.getProduct(),unit);
        	im.addItem(item);
        }
        else
        {
        	try{
        	im.addItemToContainer(item,pc);
        	}
        	catch (Exception e){return null;}
        }
        core.sendNotify(item);
        // increment barcode generator only if this
        im.incrementBarcodeGenerator();
        
		return item;
	}

	@Override
	/**
	 *  Undoes the action
	 */
	public Item undo()
	{
		core.undoAddItemPersistence(item, productAdded);
		item.setID(0);
		if(productAdded)
			item.getProduct().setID(0);
		//remove the item that was just added
		im.undoAddItem(item, productAdded);
		//and back up the barcode generator
		im.decrementBarcodeGenerator();
		//if a product was added, remove that also
		if(productAdded)
		{
			pm.deleteProduct(item.getProduct());
		}
		core.sendNotify(item);
		return item;
	}
}
